﻿using System;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;
using System.Xml;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;


namespace SmartIMS.Core
{
    public class Utils
    {
        //Ham xuat file CSV tu bang DL
        public static bool ExportCSV(DataTable dt, string pStrFilePath, bool pBlnHaveHeader, string pStrDelimitor, ref string pStrErrorMessage)
        {
            bool blnResult = false;
            try
            {
                StreamWriter objStreamWriter = new StreamWriter(pStrFilePath);
                if (pBlnHaveHeader)
                {
                    string[] arrHeaderName = new String[dt.Columns.Count];
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        arrHeaderName[i] = dt.Columns[i].ColumnName;
                        arrHeaderName[i] = GetWriteableValue(arrHeaderName[i], pStrDelimitor);
                    }
                    objStreamWriter.WriteLine(string.Join(pStrDelimitor, arrHeaderName));
                }

                for (int j = 0; j < dt.Rows.Count; j++)
                {
                    string[] arrData = new String[dt.Columns.Count];
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        object obj = dt.Rows[j][i];
                        arrData[i] = GetWriteableValue(obj, pStrDelimitor);
                    }
                    objStreamWriter.WriteLine(string.Join(pStrDelimitor, arrData));
                }
                objStreamWriter.Close();
                blnResult = true;
            }
            catch (Exception ex)
            {
                pStrErrorMessage = "Co loi xay ra khi xuat file: " + ex.Message;
            }
            return blnResult;
        }
        private static string GetWriteableValue(object pObj, string pStrDelimitor)
        {
            if (pObj == null || pObj == Convert.DBNull)
                return "";
            else if (pObj.ToString().IndexOf(pStrDelimitor) == -1)
                return pObj.ToString();
            else
                return "\"" + pObj.ToString() + "\"";
        }

        //Convert YYYYMMDD to dd/mm/yyyy
        public static string ConvertYYYYMMDDtoddmmyyyy(string strDate)
        {
            string strResult = "";
            try
            {
                Utils.WriteLog("Chuoi ngay thang(strDate): " + strDate);
                if (strDate.Length == 8) //Neu chuoi ngay thang hop le YYYYMMDD - do dai 8
                {
                    strResult = strDate.Substring(6, 2) + "/" + strDate.Substring(4, 2) + "/" + strDate.Substring(0, 4);
                    DateTime objDateTime = DateTime.Parse(strResult);
                }
                else //Neu chuoi ngay thang khong hop le - do dai != 8
                {
                    strResult = strDate;
                }
            }
            catch (Exception ex)
            {
                Utils.WriteLog(ex);
            }
            Utils.WriteLog("Chuoi ket qua(strResult): " + strResult);
            return strResult;
        }
        // Use this function to get xml string from a dataset
        public static DataSet ConvertXMLToDataSet(string xmlData)
        {
            StringReader stream = null;
            XmlTextReader reader = null;
            try
            {
                DataSet xmlDS = new DataSet();
                stream = new StringReader(xmlData);
                // Load the XmlTextReader from the stream
                reader = new XmlTextReader(stream);
                xmlDS.ReadXml(reader);
                return xmlDS;
            }
            catch
            {
                return null;
            }
            finally
            {
                if (reader != null) reader.Close();
            }
        }

        public static int GetSubBranchId(string pStrAllStaff, int pStrStaffId)
        {
            try
            {
                DataSet ddsAllStaff = new DataSet();
                ddsAllStaff = ConvertXMLToDataSet(pStrAllStaff);
                string vUnitId = GetItemAttriByID(ddsAllStaff, pStrStaffId.ToString(), "id", "unit_id");
                return StringToInt(vUnitId);
            }
            catch
            {
                return 0;
            }
        }
        public static string FormatStringNumber(string pStrNumberInteger, string pStrDelimitor, string pDecimalDelimitor, string decFormat)
        {
            //Mang gom 2 phan tu
            // Phan tu thu nhat chua so nguyen
            // Phan tu thu 2 chua so sau so thap phan            
            String[] arrStringNumber = pStrNumberInteger.Split(pStrDelimitor.ToCharArray());
            String strResult;
            String strDecmal;
            if (arrStringNumber.Length >= 2)
            {
                strResult = FormatStringInterger(arrStringNumber[0], pStrDelimitor);
                strDecmal = arrStringNumber[1];
                if (strDecmal.Length < decFormat.Length) // Dien them so 0 sau so phay
                {
                    strDecmal += decFormat.Substring(strDecmal.Length - 1, decFormat.Length - strDecmal.Length);
                }
                strResult = strResult + pDecimalDelimitor + strDecmal;
                return strResult;
            }
            else
            {
                if (decFormat.Length > 0)
                {
                    return FormatStringInterger(arrStringNumber[0], pStrDelimitor) + pDecimalDelimitor + decFormat;
                }
                else
                {
                    return FormatStringInterger(arrStringNumber[0], pStrDelimitor);
                }
            }
        }
        public static int GetBranchId(string pStrAllUnit, int pStrUnitId)
        {
            try
            {
                DataSet ddsAllUnit = new DataSet();
                ddsAllUnit = ConvertXMLToDataSet(pStrAllUnit);
                string vParentId = GetItemAttriByID(ddsAllUnit, pStrUnitId.ToString(), "id", "parent_id");
                return StringToInt(vParentId);
            }
            catch
            {
                return 0;
            }
        }
        public static string GetUserName(string pStrAllStaff, int pIntUserId)
        {
            try
            {
                DataSet ddsAllStaff = new DataSet();
                ddsAllStaff = ConvertXMLToDataSet(pStrAllStaff);
                string vUserName = GetItemAttriByID(ddsAllStaff, pIntUserId.ToString(), "id", "name");
                return vUserName;
            }
            catch
            {
                return "";
            }
        }
        ///--------------------------------------------------------------------------------------------------
        /// <summary>
        /// Them chuoi so "0" vao truoc 
        /// </summary>
        /// <param name="pStrValue">Chuoi can them</param>
        /// <param name="pIntLen">Do dai can thiet</param>
        /// <returns>Chuoi co do dai = pIntLen</returns>
        public static string Padding(string pStrValue, int pIntLen)
        {
            string strReturnValue = pStrValue;
            int len = pStrValue.Length;

            // Kiem tra do dai de cong them "0" vao truoc
            if ((pIntLen > len) && (len >= 1))
            {
                for (int i = 0; i < pIntLen - len; i++)
                {
                    strReturnValue = "0" + strReturnValue;
                }
            }
            return strReturnValue;
        }
        ///--------------------------------------------------------------------------------------------------
        /// <summary>
        /// Bo ky tu da biet
        /// </summary>
        /// <param name="pStrValue">Chuoi can loai</param>
        /// <param name="pStrSepecialChar">Chuoi cac ky tu dac biet can loai bo</param>
        /// <returns>Chuoi da duoc loai bo cac ky tu dac biet</returns>
        public static string ReplaceSepecialChar(string pStrValue, string pStrSepecialChar)
        {
            string strReturnValue = pStrValue;
            string strSepecialString = "";
            if (pStrSepecialChar != "")
            {
                strSepecialString = pStrSepecialChar;
            }
            else
            {
                strSepecialString = "~,`,!,@,#,$,%,^,&,*,\\,/,_,-";
            }
            string[] arrChar = strSepecialString.Split(',');
            int intLen = arrChar.Length;
            for (int i = 0; i < intLen; i++)
            {
                strReturnValue = strReturnValue.Replace(arrChar[i], " ");
            }
            return strReturnValue;
        }
        /// <summary>
        /// Thuc hien ghi loi ra file log
        /// </summary>
        /// <param name="pStrMessage"></param>
        public static void WriteLog(string pStrMessage)
        {
            StreamWriter log;
            string strVirtualPath = HttpContext.Current.Server.MapPath(GetParameterValue("websitePath"));

            if (!File.Exists(strVirtualPath + "log.txt"))
            {
                log = new StreamWriter(strVirtualPath + "log.txt");
            }
            else
            {
                log = File.AppendText(strVirtualPath + "log.txt");
            }

            // Write to the file:
            log.Write(DateTime.Now);
            log.Write(" : " + pStrMessage);
            log.WriteLine();
            log.Close();
        }
        /// <summary>
        /// Thuc hien ghi du lieu ra file
        /// </summary>
        /// <param name="pStrMessage"></param>
        /// <param name="pStrFileName">vi du: 'log.txt' hoac 'Message/message.txt'</param>
        public static void WriteFile(string pStrMessage, string pStrFileName)
        {
            StreamWriter log;
            string strVirtualPath = HttpContext.Current.Server.MapPath(GetParameterValue("websitePath"));

            if (!File.Exists(strVirtualPath + pStrFileName))
            {
                log = new StreamWriter(strVirtualPath + pStrFileName);
            }
            else
            {
                log = File.AppendText(strVirtualPath + pStrFileName);
            }

            // Write to the file:
            log.Write(DateTime.Now);
            log.Write(" : " + pStrMessage);
            log.WriteLine();
            log.Close();

        }
        /// <summary>
        /// Check if file is being used
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool CheckIfFileIsBeingUsed(string fileName)
        {
            try
            {
                System.IO.FileStream fs;
                fs = File.Open(fileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None);
                fs.Close();
            }
            catch
            {
                return true;
            }
            return false;

        }

        public static void WriteLog(Exception ex)
        {
            //TODO   
        }
        /// <summary>
        /// Lay gia tri cua mot tham so
        /// </summary>
        /// <param name="pParam"></param>
        /// <returns></returns>
        public static string GetParam(string pParam)
        {

            string strListId = "";
            for (int i = 0; i < HttpContext.Current.Request.Params.Count; i++)
            {
                if (ListHaveElement(HttpContext.Current.Request.Params.Keys[i], pParam, "$"))
                {
                    strListId = HttpContext.Current.Request.Params[i];
                    return strListId;
                }
            }
            return "";
        }

        /// <summary>
        /// Them dau phan cach vao chuoi so nguyen
        /// </summary>
        /// <param name="pStrNumber">Chuoi so nguyen can phan cach</param>
        /// <param name="pStrDelimitor">Ki tu phan cach</param>
        /// <returns>Chuoi so nguyen da duoc phan cach, neu xau rong thi tra ve gia tri: 0</returns>
        /// Creator: quynhnx
        public static string FormatStringInterger(string pStrNumberInteger, string pStrDelimitor)
        {
            string strResult = "";
            string strSign = "";
            int intLen = 0;
            if ((pStrNumberInteger == null) || (pStrNumberInteger == ""))
            {
                return "0";
            }
            else
            {
                strResult = pStrNumberInteger;

                // Neu da duoc phan cach roi thi khong xu li nua
                if (strResult.IndexOf(pStrDelimitor) >= 0)
                {
                    return strResult;
                }
                else
                {
                    // Loai bo cac ki tu phan cach da co (neu co)
                    strResult = strResult.Replace(".", "");
                    strResult = strResult.Replace(",", "");

                    // Cat lay dau - neu co
                    strSign = strResult.Substring(0, 1);
                    if ((strSign == "-") || (strSign == "+"))
                    {
                        strResult = strResult.Substring(1);
                    }
                    // Luu do dai chuoi
                    intLen = strResult.Length;

                    // Them dau phan cach nhom
                    for (int i = 1; i <= intLen / 3; i++)
                    {
                        strResult = strResult.Insert(intLen - i * 3, pStrDelimitor);
                    }

                    // Loai bo dau phan cach o dau tien
                    if (strResult.IndexOf(pStrDelimitor) == 0)
                    {
                        strResult = strResult.Substring(1);
                    }
                    if ((strSign == "-") || (strSign == "+"))
                    {
                        strResult = strSign + strResult;
                    }
                    return strResult;
                }
            }
        }
        

        /// <summary>
        /// Kiem tra mot phan tu co ton tai trong danh sach
        /// </summary>
        /// <param name="pStrList"></param>
        /// <param name="pStrElement"></param>
        /// <param name="pStrDelimitor"></param>
        /// <returns></returns>
        public static bool ListHaveElement(string pStrList, string pStrElement, string pStrDelimitor)
        {
            string vStrList = Utils.ObjToString(pStrList);
            string[] stringSeparators = new string[] { pStrDelimitor };
            string[] arrList = vStrList.Split(stringSeparators, StringSplitOptions.None);

            for (int i = 0; i < arrList.Length; i++)
            {
                if (string.Compare(pStrElement, arrList[i], true) == 0)
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// Them mot phan tu vao danh sach
        /// </summary>
        /// <param name="the_list"></param>
        /// <param name="the_value"></param>
        /// <param name="the_separator"></param>
        /// <returns></returns>
        public static string ListAppend(string the_list, string the_value, string the_separator)
        {
            string list = the_list;
            if (list.Trim() == "")
            {
                list = the_value;
            }
            else
                if (the_value.Trim() != "")
                {
                    list = list + the_separator + the_value;
                }
            return list;
        }

        /// <summary>
        /// Lay vitual directory
        /// </summary>
        /// <returns></returns>
        public static string GetVirtualPath()
        {
            return HttpRuntime.AppDomainAppVirtualPath;
        }

        /// <summary>
        /// Tra lai mot xau lap di lap lai count lan
        /// </summary>
        /// <param name="pStrInput"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static string StrRepeat(string pStrInput, int count)
        {
            string strTemp = "";
            for (int i = 0; i < count; i++)
                strTemp += pStrInput;
            return strTemp;
        }

        /// <summary>
        /// Tao mot danh sach
        /// </summary>
        /// <param name="pIntStart"></param>
        /// <param name="pIntEnd"></param>
        /// <param name="pIntStep"></param>
        /// <returns></returns>
        public static DataTable MakeDataTable(int pIntStart, int pIntEnd, int pIntStep)
        {
            DataTable table = new DataTable();
            DataColumn column;
            DataRow row;
            column = new DataColumn();
            column.ColumnName = "id";
            table.Columns.Add(column);

            column = new DataColumn();
            column.ColumnName = "name";
            table.Columns.Add(column);

            for (int i = pIntStart; i <= pIntEnd; i = i + pIntStep)
            {
                row = table.NewRow();
                row["id"] = i;
                row["name"] = i;
                table.Rows.Add(row);
            }
            return table;
        }

        /// <summary>
        /// Sinh ra danh sach cac trang
        /// </summary>
        /// <param name="pIntNumberRecordPerPage">So ban ghi tren mot trang</param>
        /// <param name="pIntTotalRecord">Tong so ban ghi</param>
        /// <returns></returns>
        public static DataTable GeneratePage(int pIntNumberRecordPerPage, int pIntTotalRecord)
        {
            DataTable table = new DataTable();
            DataColumn column;
            DataRow row;
            column = new DataColumn();
            column.ColumnName = "id";
            table.Columns.Add(column);

            column = new DataColumn();
            column.ColumnName = "name";
            table.Columns.Add(column);

            int intNumberPage = 0;
            if (pIntTotalRecord % pIntNumberRecordPerPage == 0)
            {
                intNumberPage = (pIntTotalRecord / pIntNumberRecordPerPage);
            }
            else
            {
                intNumberPage = (pIntTotalRecord / pIntNumberRecordPerPage) + 1;
            }
            if (pIntTotalRecord == 0) intNumberPage = 1;

            for (int i = 1; i <= intNumberPage; i++)
            {
                row = table.NewRow();
                row["id"] = i;
                row["name"] = i;
                table.Rows.Add(row);
            }
            return table;
        }
        /// <summary>
        /// Chuyen xau sang so Int
        /// </summary>
        /// <param name="pStrString"></param>
        /// <returns>int</returns>
        public static int StringToInt(string pStrString)
        {
            int intValue;
            try
            {
                intValue = int.Parse(pStrString);
            }
            catch (FormatException)
            {
                intValue = 0;
            }
            catch (OverflowException)
            {
                intValue = 0;
            }
            catch (Exception)
            {
                intValue = 0;
            }
            return intValue;
        }
        /// <summary>
        /// Chuyen xau sang so Long
        /// </summary>
        /// <param name="pStrString"></param>
        /// <returns>int</returns>
        public static long StringToLong(string pStrString)
        {
            long longValue = 0;
            try
            {
                longValue = long.Parse(pStrString);
            }
            catch (Exception)
            {
                longValue = 0;
            }
            return longValue;
        }
        /// <summary>
        /// Chuyen xau sang so Double
        /// </summary>
        /// <param name="pStrString"></param>
        /// <returns>int</returns>
        public static double StringToDouble(string pStrString)
        {
            double doubletValue = 0;
            try
            {
                doubletValue = double.Parse(pStrString);
            }
            catch (Exception)
            {
                doubletValue = 0;
            }
            return doubletValue;
        }
        /// <summary>
        /// Chuyen xau sang so Float
        /// </summary>
        /// <param name="pStrString"></param>
        /// <returns>int</returns>
        public static float StringToFloat(string pStrString)
        {
            float fltValue;
            try
            {
                fltValue = float.Parse(pStrString);
            }
            catch (FormatException)
            {
                fltValue = 0;
            }
            catch (OverflowException)
            {
                fltValue = 0;
            }
            catch (Exception)
            {
                fltValue = 0;
            }
            return fltValue;
        }


        /// <summary>
        /// Chuyen DateTime sang xau
        /// </summary>
        /// <param name="pStrString"></param>
        /// <returns>int</returns>    
        public static string DateTimeToString(string pStrString)
        {
            string vTemp = "";
            try
            {
                vTemp = System.Convert.ToDateTime(pStrString).ToString("dd/mm/yyyy");
            }
            catch (Exception)
            {
                vTemp = "";
            }
            return vTemp;
        }

        /// <summary>
        /// Thay cho ham ToString() mac dinh
        /// </summary>
        /// <param name="pObj"></param>
        /// <returns>int</returns>
        public static string ObjToString(object pObj)
        {
            string strResult = "";
            try
            {
                strResult = pObj.ToString();
            }
            catch (Exception)
            {
                strResult = "";
            }
            return strResult;
        }

        /// <summary>
        /// Sinh ra xau Sql de thuc thi tu doi tuong chua cac tham so
        /// </summary>
        /// <param name="pObjCom"></param>
        /// <returns>string</returns>
        public static string GenerateSqlString(OracleCommand pObjCom)
        {
            string vTemp = "";
            vTemp = vTemp + pObjCom.CommandText + '(';
            for (int i = 0; i < pObjCom.Parameters.Count; i++)
            {
                if (pObjCom.Parameters[i].DbType.ToString() == "Varchar2")
                {
                    vTemp = vTemp + "'" + pObjCom.Parameters[i].Value + "'";
                }
                else
                {
                    vTemp = vTemp + pObjCom.Parameters[i].Value;
                }
                if (i < pObjCom.Parameters.Count - 1)
                {
                    vTemp = vTemp + ",";
                }

            }
            vTemp = vTemp + ')';
            return vTemp;
        }
        
        public static string GetItemAttriByID(DataSet ddsList, string pIntValueCompare, string pStrAttriCompare, string pStrAttri)
        {
            if (ddsList.Tables.Count > 0)
            {
                for (int i = 0; i < ddsList.Tables[0].Rows.Count; i++)
                {
                    if (ddsList.Tables[0].Rows[i][pStrAttriCompare].ToString() == pIntValueCompare)
                    {
                        return ddsList.Tables[0].Rows[i][pStrAttri].ToString();
                    }
                }
            }
            return "";
        }

        

        public static byte[] GetFileContent(string pStrFilePath)
        {

            FileStream fs = new FileStream(pStrFilePath, FileMode.Open, FileAccess.Read);


            byte[] b = new byte[fs.Length - 1];


            fs.Read(b, 0, b.Length);


            fs.Close();

            return b;
        }
        /// <summary>
        /// So sanh ngay, ngay dinh dang: dd/mm/yyyy va ngay phai hop le
        /// </summary>
        /// <param name="pStrDate1">Tu ngay</param>
        /// <param name="pStrDate2">Den ngay</param>
        /// <returns>pStrDate1 - pStrDate2</returns>
        public static int CompareDate(string pStrDate1, string pStrDate2)
        {
            System.IFormatProvider format = new System.Globalization.CultureInfo("vi-VN", true);
            return DateTime.Compare(DateTime.Parse(pStrDate1, format, System.Globalization.DateTimeStyles.AllowWhiteSpaces), DateTime.Parse(pStrDate2, format, System.Globalization.DateTimeStyles.AllowWhiteSpaces));
        }
        public static int DayDiff(string pStrDate1, string pStrDate2)
        {
            System.IFormatProvider format = new System.Globalization.CultureInfo("vi-VN", true);
            TimeSpan ts = DateTime.Parse(pStrDate1, format, System.Globalization.DateTimeStyles.AllowWhiteSpaces).Subtract(DateTime.Parse(pStrDate2, format, System.Globalization.DateTimeStyles.AllowWhiteSpaces));
            return ts.Days;
        }

        public static bool IsDate(string strDate)
        {
            bool blnResult = false;
            try
            {
                DateTime.Parse(strDate);
                blnResult = true;
            }
            catch
            {
                blnResult = false;
            }
            return blnResult;
        }
        ///-----------------------------------------------------------------------------------
        /// <summary>
        /// Ham doc mot chuoi co doi dai toi da la 3
        /// </summary>
        /// <param name="pStrKey"></param>
        /// <returns></returns>
        public static string Len3ToString(string pStrInt)
        {
            string strNumber = "";
            int len = pStrInt.Length;
            char[] arr = new char[5];
            if ((pStrInt == "000") || (pStrInt == ""))
            {
                return strNumber;
            }
            else
            {
                arr = pStrInt.ToCharArray();
                switch (arr[0])
                {
                    case '0':
                        if (len == 3 || len == 1)
                        {
                            strNumber += " không";
                        }
                        break;

                    case '1':
                        if (len == 2)
                        {
                            strNumber += " mười";
                        }
                        else
                        {
                            strNumber += " một";
                        }
                        break;
                    case '2':
                        strNumber += " hai";
                        break;
                    case '3':
                        strNumber += " ba";
                        break;
                    case '4':
                        strNumber += " bốn";
                        break;
                    case '5':
                        strNumber += " năm";
                        break;
                    case '6':
                        strNumber += " sáu";
                        break;
                    case '7':
                        strNumber += " bẩy";
                        break;
                    case '8':
                        strNumber += " tám";
                        break;
                    case '9':
                        strNumber += " chín";
                        break;
                }
                if (len == 3)
                {
                    // hàng Trăm
                    strNumber += " trăm";
                }
                if (len == 2)
                {
                    if ((arr[0] != '0') && (arr[0] != '1'))
                    {
                        strNumber += " mươi";
                    }
                }
                // Hàng Chục
                if (len >= 2)
                {
                    switch (arr[1])
                    {
                        case '1':
                            if (len == 3)
                            {
                                strNumber += " mười";
                            }
                            if ((len == 2) && (arr[0] != '1'))
                            {
                                strNumber += " mốt";
                            }
                            if ((len == 2) && (arr[0] == '1'))
                            {
                                strNumber += " một";
                            }
                            break;
                        case '2':
                            strNumber += " hai";
                            break;
                        case '3':
                            strNumber += " ba";
                            break;
                        case '4':
                            //if (len == 2)
                            //{
                            //    strNumber += " tư";
                            //}
                            //else
                            //{
                            strNumber += " bốn";
                            //}
                            break;
                        case '5':
                            if (len == 2)
                            {
                                strNumber += " lăm";
                            }
                            else
                            {
                                strNumber += " năm";
                            }
                            break;
                        case '6':
                            strNumber += " sáu";
                            break;
                        case '7':
                            strNumber += " bẩy";
                            break;
                        case '8':
                            strNumber += " tám";
                            break;
                        case '9':
                            strNumber += " chín";
                            break;
                    }
                    if (len == 3)
                    {
                        if ((arr[1] != '0') && (arr[1] != '1'))
                        {
                            strNumber += " mươi";
                        }
                        if ((arr[1] == '0') && (arr[2] != '0'))
                        {
                            strNumber += " linh";
                        }
                    }
                }
                // Hàng đơn vị
                if (len == 3)
                {
                    switch (arr[2])
                    {
                        case '1':
                            if (arr[1] != '0')
                            {
                                strNumber += " mốt";
                            }
                            else
                            {
                                strNumber += " một";
                            }
                            break;
                        case '2':
                            strNumber += " hai";
                            break;
                        case '3':
                            strNumber += " ba";
                            break;
                        case '4':
                            //if ((arr[1] != '0') && (arr[1] != '1'))
                            //{
                            //    strNumber += " tư";
                            //}
                            //else
                            //{
                            strNumber += " bốn";
                            //}
                            break;
                        case '5':
                            if (arr[1] != '0')
                            {
                                strNumber += " lăm";
                            }
                            else
                            {
                                strNumber += " năm";
                            }
                            break;
                        case '6':
                            strNumber += " sáu";
                            break;
                        case '7':
                            strNumber += " bẩy";
                            break;
                        case '8':
                            strNumber += " tám";
                            break;
                        case '9':
                            strNumber += " chín";
                            break;
                    }
                }
                return strNumber;
            }
        }
        public static bool IsDate(string value, string format)
        {
            if (format.ToLower() == "dd/mm/yyyy")
            {
                string strRegex = @"^(?=\d)(?:(?:31(?!.(?:0?[2469]|11))|(?:30|29)(?!.0?2)|29(?=.0?2.(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))(?:\x20|$))|(?:2[0-8]|1\d|0?[1-9]))([-./])(?:1[012]|0?[1-9])\1(?:1[6-9]|[2-9]\d)?\d\d(?:(?=\x20\d)\x20|$))?(((0?[1-9]|1[012])(:[0-5]\d){0,2}(\x20[AP]M))|([01]\d|2[0-3])(:[0-5]\d){1,2})?$";
                Regex re = new Regex(strRegex);
                if (re.IsMatch(value))
                    return (true);
                else
                    return (false);
            }
            else
            {
                return (true);
            }
        }
        ///-----------------------------------------------------------------------------------
        /// <summary>
        /// Ham doc mot chuoi co doi dai bat ky
        /// </summary>
        /// <param name="pStrNumeric">Chuoi so da duoc</param>
        /// <returns>Chuỗi đọc số</returns>
        public static string NumericIntToString(string pStrNumeric)
        {
            string strNumber = "";
            string strReadNumber = "";
            string strRead3 = "";
            char[] arr = new char[100];
            int i = 0;
            int count = 0;
            int len = 0;
            int len3 = 0;
            int mod3 = 0;
            // Loại bỏ dấu phân cách nhóm
            strNumber = pStrNumeric.Replace(",", "");
            strNumber = strNumber.Replace(".", "");

            // Loại bỏ số 0 đứng đầu
            arr = strNumber.ToCharArray();
            for (i = 0; i < arr.Length; i++)
            {
                if (arr[i] == 0)
                {
                    count++;
                }
                else
                {
                    break;
                }
            }
            strNumber = strNumber.Substring(count);

            // Doc chuoi so
            len = strNumber.Length;
            // Dem bo so 3
            len3 = len / 3;
            mod3 = len % 3;

            // Neu doi dai chuoi la 0 thi gan la so 0
            if (len == 0)
            {
                strNumber = "0";
                mod3 = 1;
            }
            // Doc bo so dau tien
            strRead3 = Len3ToString(strNumber.Substring(0, mod3));
            strReadNumber = strRead3;
            for (i = 0; i < len3; i++)
            {
                if (((3 * (len3 - i)) % 9 == 0) && (strReadNumber.Length > 0))
                {
                    strReadNumber += " tỷ";
                }
                if (strRead3.Length > 0)
                {
                    if ((3 * (len3 - i)) % 9 == 6)
                    {
                        strReadNumber += " triệu";
                    }
                    if (((3 * (len3 - i)) % 9 == 3))
                    {
                        strReadNumber += " nghìn";
                    }
                }
                // Đọc chuỗi 3 kí tự
                strRead3 = Len3ToString(strNumber.Substring(mod3 + i * 3, 3));
                // Luu chuỗi còn lại
                //strNumber = strNumber.Substring(mod3 + i * 3);
                // Gán vào chuỗi kết quả đọc
                strReadNumber += strRead3;
            }

            return strReadNumber.Substring(1, 1).ToUpper() + strReadNumber.Substring(2);
        }


        /// <summary>
        /// Lay gia tri cua mot khoa
        /// </summary>
        /// <param name="pStrKey"></param>
        /// <returns></returns>
        public static string GetParameterValue(string pStrKey)
        {
            string strAppCode = ConfigurationManager.AppSettings.Get(pStrKey);
            return (string)strAppCode;

        }

    }
    
}
